local app = require "app"
local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent

local payout_system = class("payout_system", slot_system)

function payout_system:initialize()
    local chip_anim = require "ui.Widget.chip_anim"
    self.chip_anim = chip_anim.new();

    -- TODO:到这里时pay_tip还没有被inject到ingame，system不应该依赖UI
    local pay_tip = self.ingame.pay_tip or {};
    local last_win = self.ingame.hud.last_win;
    self.context.machine:replace(components.payout_component, 0, pay_tip, last_win)
end

function payout_system:get_trigger()
    return {{Matcher({components.payout_component}), GroupEvent.ADDED}};
end

function payout_system:filter(entity)
    return entity:has(components.payout_component);
end

local function freespin_payout(self, freespin_component)
    if freespin_component.left_times == 0 then
        self.ingame.hud.freespin:update_value(freespin_component.total_value);
        self:wait(0.5);
        self.chip_anim:play(self.ingame.hud.freespin.win_txt.transform, self.ingame.hud.player_info.chip_txt.transform, math.random(3,5));
        self:wait(2);

        self.ingame.hud:on_over_free();
        freespin_component.in_free = false;
        self.ingame.hud.freespin:update_value(0);
    else
        self.ingame.hud.freespin:update_value(freespin_component.total_value);
    end
end

function payout_system:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return;
    end

    entitas:foreach(function(e)
        if e:has(components.freespin_component) then
            local freespin_component = e:get(components.freespin_component);
            if freespin_component.in_free then
                freespin_payout(self, freespin_component);
                return;
            end
        end
        --local indexes = e:get(components.indexes_component).indexes;
        local payout_data = e:get(components.payout_component)
        local payout = payout_data.payout;
        local txt = payout_data.tip_txt;
        local last_win = payout_data.last_win;
        if payout > 0 then
            last_win:set_value(payout);
            --self.chip_anim:play(self.ingame.jackpot_value.transform, self.ingame.hud.player_info.transform, math.random(3,5));
            if txt then
                --txt.text = string.format("%s, %s, %s 赔付$%s", indexes[1], indexes[2], indexes[3], payout);
            end
        else
            if txt then
                txt.text = app.i18n.text("slot:good luck")
            end
        end
    end)
end

function payout_system:tear_down()
    --self.chip_anim:stop();
end

return payout_system
